import { createRouter, createWebHashHistory } from 'vue-router';
import Home from '../components/Home.vue';
import Login from '../components/Login.vue';
import { useAuthStore } from '../store/auth';


const routes = [
  { path: '/', component: Home, meta: { requiresAuth: true } },
  { path: '/login', component: Login },
  { 
    path: '/todo', 
    component: () => import('../components/todolist.vue')
      .catch(err => {
        console.error('Failed to load todo component:', err);
        return { template: '<div>加载失败</div>' };
      }), 
    meta: { requiresAuth: true } 
  },
  // 对其他异步组件也添加类似的错误处理
  { path: '/profile', component: () => import('../components/Profile.vue'), meta: { requiresAuth: true } },
  { path: '/gallery', component: () => import('../components/ImageGallery.vue'), meta: { requiresAuth: true } },
  { path: '/image/:id', component: () => import('../components/ImageDetail.vue'), meta: { requiresAuth: true } }
];

const router = createRouter({
  history: createWebHashHistory(),  // 修改这里
  routes
});

// 修改路由守卫，使用 _ 表示未使用的参数
router.beforeEach((to, _, next) => {
  const authStore = useAuthStore();
  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    next('/login');
  } else {
    next();
  }
});

export default router;